package com.restkeeper.store.mapper;

import java.time.LocalDate;
import java.util.*;

public class MyTest {

    public static void main(String[] args) {
        String[] dateArr = {"2018-04-05","2019-01-01","2018-04-05","2018-04-03","2018-04-20","2018-05-03","2018-05-02","2018-04-04","2018-04-05"};

        //对所有日期字符串重排序
        TreeSet<String> dateSet = new TreeSet<>(Arrays.asList(dateArr));

        //将日期字符串转为日期
        List<LocalDate> dateList = new ArrayList<>();
        for (String dateStr : dateSet) {
            LocalDate dateTime = LocalDate.parse(dateStr);
            dateList.add(dateTime);
        }


        //存储每个时间段对应的日期集合
        Map<String,TreeSet<String>> map = new TreeMap<>();
        for (int i = 0; i < dateList.size(); i++) {
            LocalDate date01 = dateList.get(i); //比较的第一个日期
            String date01Str = date01.toString();

            if(i<dateList.size()-1){
                String mapKey = date01.toString();

                LocalDate date02 = dateList.get(i + 1); //比较的第二个日期
                String date02Str = date02.toString();

                TreeSet<String> treeSet = new TreeSet<>();
                //如果两个日期连续，就判断第一个日期在MAP的SET值里是否存在，如果已存在则把这个存在的值对应的KEY，当做本次的KEY
                if(date02.getDayOfMonth()-date01.getDayOfMonth()==1){
                    for(String key : map.keySet()){
                        treeSet = map.get(key);
                        if(treeSet.contains(date01Str)){
                            mapKey = key;
                            break;
                        }
                    }
                    treeSet.add(date01Str);  //添加第一个日期字符串
                    treeSet.add(date02Str); //添加第二个日期字符串
                } else { //否则，说明日期不连续，那么key就是第二个日期的字符串，值也是第二个日期的支付查
                    mapKey = date02Str;
                    treeSet.add(date02Str); //添加第二个日期字符串
                }
                map.put(mapKey, treeSet);
            }

        }

        //遍历MAP将最终输出的描述信息组装
        List<String> descList = new ArrayList<>();
        for(String key : map.keySet()){
            TreeSet<String> set = map.get(key);
            if(set.size()==1){
                descList.add(key);
            } else {
                descList.add(set.first()+"至"+set.last());
            }
        }

        System.out.println("返回结果：" + descList);
    }
}
